package pager

import (
	"strings"

	"entgo.io/ent/dialect/sql"
)

type SortDirection string

var (
	SortDirectionAsc  SortDirection = "asc"
	SortDirectionDesc SortDirection = "desc"
)

type Req struct {
	PageSize  int    `json:"page_size" form:"page_size"`
	PageIndex int    `json:"page_index" form:"page_index"`
	Sorting   string `json:"sorting" form:"sorting"`
	Keyword   string `json:"keyword" form:"keyword"`
}

func (r *Req) GetOffset() int {
	if r.PageIndex < 1 {
		return 0
	}
	return (r.PageIndex - 1) * r.GetLimit()
}

func (r *Req) GetLimit() int {
	if r.PageSize <= 0 {
		return 10
	}
	return r.PageSize
}

func (r *Req) GetOrderOptions() []func(*sql.Selector) {
	var orderOpts []func(*sql.Selector)
	if strings.TrimSpace(r.Sorting) != "" {
		arr := strings.Split(r.Sorting, ",")
		for _, v := range arr {
			v = strings.TrimSpace(v)
			if strings.Contains(v, " ") {
				varr := strings.Split(v, " ")
				varr[1] = strings.ToLower(varr[1])
				switch SortDirection(varr[1]) {
				case SortDirectionDesc:
					orderOpts = append(orderOpts, sql.OrderByField(varr[0], sql.OrderDesc()).ToFunc())
				default:
					orderOpts = append(orderOpts, sql.OrderByField(v, sql.OrderAsc()).ToFunc())
				}
			} else {
				orderOpts = append(orderOpts, sql.OrderByField(v, sql.OrderAsc()).ToFunc())
			}
		}
	} else {
		orderOpts = []func(*sql.Selector){
			sql.OrderByField("id", sql.OrderDesc()).ToFunc(),
			sql.OrderByField("last_modification_time", sql.OrderDesc()).ToFunc(),
		}
	}
	return orderOpts
}
